<?php
/**
 * Created by PhpStorm.
 * User: qingmu-523
 * Date: 2018/10/17
 * Time: 17:53
 */

namespace App\Command;


use App\Config\Db;
use Carbon\Carbon;
use PDO;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class CreateReturnTmcCommand extends BaseCommand
{
    private $is_all = true;
    private $part_sku = [];
    protected function configure()
    {
        $endTime = Carbon::now("Asia/Shanghai");
        $startTime = Carbon::now("Asia/Shanghai")->subMinute(10);
        $this
            ->setName('app:create-return-tmc')
            ->setDescription('创建tmc订单的售后单信息，退货/退款')
            ->setHelp("创建tmc订单的售后单信息")// configure an argument / 配置一个参数
            ->addOption("has_good_return", 'hgr', InputOption::VALUE_REQUIRED, "是否退货，true表退货，false表退款", false)
            ->addOption("tid", '', InputOption::VALUE_OPTIONAL, "为该tid的订单生成售后tmc信息", 0)
            ->addOption("is_all", '', InputOption::VALUE_OPTIONAL, "全单退款/退货", "true")
            ->addOption("part_sku", '', InputOption::VALUE_OPTIONAL, '部分sku&个数,例如:[{"sku":"123456","num":1}]', '[]')
            ->addOption("startTime", "", InputOption::VALUE_REQUIRED, "截取订单开始时间，默认查找前十分钟", $startTime)
            ->addOption("endTime", "", InputOption::VALUE_REQUIRED, "截取订单结束时间，默认查找前十分钟", $endTime);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        date_default_timezone_set("Asia/Shanghai");
        $has_good_return = $input->getOption("has_good_return");
        $tid = $input->getOption('tid');
        $this->is_all = $input->getOption('is_all');
        $this->part_sku = json_decode($input->getOption('part_sku'),true);
        $startTime = $input->getOption('startTime');
        $endTime = $input->getOption('endTime');
        $helper = $this->getHelper('question');
        var_dump($this->part_sku);
        var_dump($this->is_all);
        var_dump(empty($this->part_sku));
        if($this->is_all =='false' && empty($this->part_sku)){
            echo "部分退需要正确输入sku数据\n\r";
            die;
            exit(1);
        }
        $question = new ConfirmationQuestion('Whether to push directly into the redis queue?', false);

        $has_push_redis = false;
        if (!$helper->ask($input, $output, $question)) {
            $has_push_redis = false;
        } else {
            $has_push_redis = true;
        }
        $start_time = time();
        if ($tid != 0) {
            $info = $this->tmcdb->query("select * from jdp_tb_trade where tid = '$tid' ")->fetchAll(PDO::FETCH_ASSOC);
//            print_r($info);
            if (!$info){
                echo "检查jdp_tb_trade表是否存在tid:".$tid;
                exit;
            }
            $this->create_return($info[0],$has_good_return,$has_push_redis);
//            $return_data = $this->create_return($info[0]['tid'],$info[0]['oid'],$info[0]['seller_nick'],$info[0]['buyer_nick'],$has_good_return);
//            print_r($return_data);
        } else {
            for ($i = 0; ; $i++) {
                $sql = "select * from jdp_tb_trade  where jdp_created >= '$startTime' and jdp_created <='$endTime' limit ";
                $page_size = 100;
                $start = $i * $page_size;
//                echo "$sql $start,$page_size";
//                if ($i==0)exit;
                $infos = $this->tmcdb->query("$sql $start,$page_size")->fetchAll(PDO::FETCH_ASSOC);
                if (empty($infos)){
                    echo "查询结束\n\r";
                    exit(1);
                }
                foreach ($infos as $item) {
//                    $return_data = $this->create_return($item['tid'],$item,$item['seller_nick'],$item['buyer_nick'],$has_good_return);
                    $this->create_return($item,$has_good_return,$has_push_redis);
                }
            }
        }
        $end_time = time();
        $output->writeln("结束时间：".$end_time);
        $output->writeln("耗时时间：".($end_time-$start_time));

        $output->writeln([
            'Order Creator',
            '============',
            '',
        ]);

        // outputs a message followed by a "\n"
        $output->writeln('Success!');


//        $process = new Process(array('figlet', 'Symfony'));
//
//        $helperprocess->run($output, $process);
//        sleep(2);
//        $progress = new ProgressBar($output);
////        $progress->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
//
//        // start and displays the progress bar
//        // 启动并显示进度条
//        $progress->start();
//        sleep(2);
//        $progress->advance();
//        $progress->finish();
    }

    function add_queue($item,$has_push_redis)
    {
        if (!$has_push_redis) {
            return;
        }
        $data = array(
            //'data' => array(
            'buyer_nick' => $item['buyer_nick'],
            'payment' => "0.00",
            'end_time' => microtime(),
            'status' => $item['status'],
            'iid' => $item['oid'],
            'oid' => $item['oid'],
            'pay_time' => microtime(),
            'tid' => $item['tid'],
            'type' => $item['jdp_response'],
            'post_fee' => $item['jdp_response'],
            'seller_nick' => $item['seller_nick'],
            'topic' => 'taobao_refund_RefundBuyerReturnGoods',
            'nick' => $item['seller_nick'],
            'time' => microtime(),
            'refund_id' => $item['refund_id']
            //  ),
        );
        $this->do_queue('taobaomsg', 'add', $data);
    }

    function create_return($item,$has_good_return,$has_push_redis)
    {
        date_default_timezone_set("Asia/Shanghai");
        //从转单或推送单获取一笔天猫外部订单号
        //refund_id 退款淘宝单号
        $jdp_response = json_decode($item['jdp_response'],true);
        $orders = $jdp_response['trade_fullinfo_get_response']['trade']['orders']['order'];
        $tid = $item['tid'];
        $seller_nick = $item['seller_nick'];
        $buyer_nick = $item['buyer_nick'];
        $dt = date("Y-m-d H:i:s");
        $jdp_hashcode = time();
        if($this->is_all == 'true'){
            foreach($orders as $order){
                $refund_id = $this->getMillisecond() . mt_rand(1, 9999);
                //获取创建时间的跨越度，为一天前-至当前的上海时区
                //jdp_hashcode哈希码
                $name = $buyer_nick;
                $responeJson = $this->generatedRefundInfo($refund_id, $tid,$order, $dt, $seller_nick, $name, $has_good_return);

                $creator = [
                    "refund_id" => $refund_id,
                    "seller_nick" => $seller_nick,
                    "buyer_nick" => $name,
                    "status" => "WAIT_SELLER_AGREE",
                    "created" => $dt,
                    "tid" => $tid,
                    "oid" => $order['oid'],
                    "modified" => $dt,
                    "jdp_hashcode" => $jdp_hashcode,
                    "jdp_response" => $responeJson,
                    "jdp_created" => $dt,
                    "jdp_modified" => $dt,
                ];
                $this->add_queue($creator,$has_push_redis);
                // unset($responeJson);//用完及时销毁
                $bool = $this->tmcdb->insert("jdp_tb_refund", $creator);
            }
        }else{
            $sku_orders = [];
            foreach($orders as $order){
                $sku_orders[$order['outer_sku_id']] = $order;
            }
            $part_orders = [];
            //选出对应的需要退的sku
            foreach($this->part_sku as $item){
                $select_order = $sku_orders[$item['sku']];
                $pay_one = $select_order['payment']/$select_order['num'];
                $select_order['num'] = $item['num'];
                $select_order['payment'] = $item['num']*$pay_one;
                $part_orders[] = $select_order;
            }

            foreach($part_orders as $order){
                $refund_id = $this->getMillisecond() . mt_rand(1, 9999);
                //获取创建时间的跨越度，为一天前-至当前的上海时区
                //jdp_hashcode哈希码
                $name = $buyer_nick;
                $responeJson = $this->generatedRefundInfo($refund_id, $tid,$order, $dt, $seller_nick, $name, $has_good_return);

                $creator = [
                    "refund_id" => $refund_id,
                    "seller_nick" => $seller_nick,
                    "buyer_nick" => $name,
                    "status" => "WAIT_SELLER_AGREE",
                    "created" => $dt,
                    "tid" => $tid,
                    "oid" => $order['oid'],
                    "modified" => $dt,
                    "jdp_hashcode" => $jdp_hashcode,
                    "jdp_response" => $responeJson,
                    "jdp_created" => $dt,
                    "jdp_modified" => $dt,
                ];
                $this->add_queue($creator,$has_push_redis);
                // unset($responeJson);//用完及时销毁
                $bool = $this->tmcdb->insert("jdp_tb_refund", $creator);
            }
        }
    }

    function generatedRefundInfo($refund_id, $tid,$order, $dt, $seller_nick, $name, $has_good_return)
    {
        $i = $this->omsdb->select("set_package_list",['sku','outer_id'],['sku'=>$order['outer_sku_id']]);
        $out_id = $order['outer_sku_id'];
        if(count($i) != 0){
            $out_id = $i[0]["outer_id"];
        }
        var_dump($out_id);
        //    var_dump($i);die;
        $respone = [
            "refund_get_response" => [
                "refund" => [
                    "refund_id" => $refund_id,
                    //WAIT_SELLER_AGREE(买家已经申请退款，等待卖家同意) WAIT_BUYER_RETURN_GOODS(卖家已经同意退款，等待买家退货) WAIT_SELLER_CONFIRM_GOODS(买家已经退货，等待卖家确认收货) SELLER_REFUSE_BUYER(卖家拒绝退款) CLOSED(退款关闭) SUCCESS(退款成功)
                    "status" => "WAIT_SELLER_AGREE",
                    "seller_nick" => $seller_nick,
                    "buyer_nick" => $name,
                    "tid" => $tid,
                    "oid" => $order['oid'],
                    "created" => "广东省广州市敦和路189号海珠科技园2期1号楼",
                    "modified" => $dt,
                    "buyer_email" => $dt,
                    "address" => "H&amp;M物流， 4009208822， 江苏省苏州市昆山市 花桥镇新生路718号（近沿沪大道）江苏富莱德仓储有限公司，H&amp;M/LF物流\r\n仓库A3， 215300",
                    "advance_status" => 0,
                    "alipay_no" => "2018041821001001530537212881",
                    "attribute" => ";EXmrf:6085;ttid:h5;tod:604800000;reason:11;agreeReturnAuto:1;apply_text_id:501431;newRefund:rp2;bizCode:tmall.general.refund;b2c:1;stopTimeout:1;tos:3;seller_agreed_refund_fee:6085;old_reason_id:11;logisticsCompanyName:EMS;seller_batch:true;leavesCat:50013618;itemBuyAmount:1;rightsSuspend:1;logisticsOrderCode:1147022026013;seller_audit:0;isAdvContChecked:1;ol_tf:6085;ee_trace_id:0bfa02ba15244496942694348e09f5;opRole:daemon;apply_init_refund_fee:6085;commonFetchOrderStatus:1;isVirtual:0;itemPrice:7990;sku:3575813401681|颜色分类#3B浅牛仔蓝#3A参考身高#3B86cm;interceptStatus:0;shop_name:HM官方旗舰店;refundFrom:1;appName:pyramid;restartForXiaoer:1;abnormal_dispute_status:0;payMode:alipay;listDisplayfetchStatus:40;workflowName:return_and_refund;7d:1;sgr:1;userCredit:6;enfunddetail:1;rootCat:50008165;bgmtc:2018-04-18 13#3B09#3B44;",
                    "company_name" => "天天快递",
                    "cs_status" => 1,
                    "desc" => "",
                    //可选值BUYER_NOT_RECEIVED (买家未收到货) BUYER_RECEIVED (买家已收到货) BUYER_RETURNED_GOODS (买家已退货)
                    "good_status" => "BUYER_RECEIVED",
                    "has_good_return" => $has_good_return, //true表退货，false表退款
                    "num" => $order['num'],
                    "num_iid" => 565178399431,
                    "operation_contraint" => "null",
                    //TRADE_NO_CREATE_PAY(没有创建支付宝交易) WAIT_BUYER_PAY(等待买家付款) WAIT_SELLER_SEND_GOODS(等待卖家发货,即:买家已付款) WAIT_BUYER_CONFIRM_GOODS(等待买家确认收货,即:卖家已发货) TRADE_BUYER_SIGNED(买家已签收,货到付款专用) TRADE_FINISHED(交易成功) TRADE_CLOSED(交易关闭) TRADE_CLOSED_BY_TAOBAO(交易被淘宝关闭) ALL_WAIT_PAY(包含：WAIT_BUYER_PAY、TRADE_NO_CREATE_PAY) ALL_CLOSED(包含：TRADE_CLOSED、TRADE_CLOSED_BY_TAOBAO)
                    "order_status" => "WAIT_SELLER_SEND_GOODS",
                    "outer_id" => "0566449",
                    "payment" => $order['payment'],
                    "price" => ($order['payment']/$order['num']),
                    "reason" => "7天无理由退换货",
                    "refund_fee" => ($order['payment']),
                    "refund_phase" => "onsale",
                    "refund_version" => 1524449694487,
                    "sku" => "{$out_id}|{$order['sku_properties_name']}",
                    "title" => $order['title'],
                    "total_fee" => $order['total_fee'],
                ],
            ],
        ];

        $responeJson = json_encode($respone, JSON_UNESCAPED_UNICODE);
        return $responeJson;
    }


}